<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select v-model="formData.deviceId" placeholder="请输入设备名称进行搜索" filterable style="width: 100%" remote
                :remote-method="deviceRemoteMethod" :loading="deviceLoading" @change="handleDeviceChange">
                <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="故障类型" prop="faultTypeId">
              <el-cascader
                v-model="faultTypePath"
                :options="faultTypeOptions"
                :props="{
                  checkStrictly: true,
                  lazy: true,
                  lazyLoad: lazyLoadFaultType
                }"
                clearable
                placeholder="请选择故障类型"
                @change="handleFaultTypeChange"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="故障内容">
              <Editor v-model="formData.faultContent" :min-height="192" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行状态" prop="executeStatus">
              <el-select v-model="formData.executeStatus" placeholder="请选择执行状态" clearable size="small" style="width: 100%;">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.EXECUTE_STATUS)" :key="dict.value" :label="dict.label"
                           :value="parseInt(dict.value)"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="实际执行人" prop="actualExecutorUserId">
              <el-select v-model="formData.actualExecutorUserId" placeholder="请选择实际执行人" filterable style="width: 100%"
                remote :remote-method="actualRemoteMethod" :loading="actualUserLoading" @change="handleActualExecutorChange">
                <el-option v-for="user in actualUserList" :key="user.id" :label="user.nickname || user.username" :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="完成时间" prop="finishTime">
              <el-date-picker clearable v-model="formData.finishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择完成时间" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次维修时间" prop="lastMaintenanceTime">
              <el-date-picker clearable v-model="formData.lastMaintenanceTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择上次维修时间" style="width: 100%;"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaintenanceRecordsApi from '@/api/devices/maintenancerecords/index.js';
import * as UserApi from '@/api/system/user';
import * as DeviceApi from '@/api/system/device';
import * as FaultTypeApi from '@/api/devices/faulttype';
import Editor from '@/components/Editor';
import { getDictDatas,getDictDataLabel, DICT_TYPE } from '@/utils/dict'
export default {
  name: "MaintenanceRecordsForm",
  components: {
    Editor,
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 实际执行人列表
      actualUserList: [],
      // 实际执行人加载状态
      actualUserLoading: false,
      // 设备列表
      deviceList: [],
      // 设备加载状态
      deviceLoading: false,
      // 故障类型选项（用于级联组件）
      faultTypeOptions: [],
      // 故障类型路径
      faultTypePath: [],
      // 表单参数
      formData: {
        id: undefined,
        deviceId: undefined,
        deviceCode: undefined,
        deviceName: undefined,
        faultTypeId: undefined,
        faultTypeCode: undefined,
        faultTypeName: undefined,
        faultContent: undefined,
        status: 0, // 新建时默认状态为0
        executeStatus: 0, // 新建时默认执行状态为0
        actualExecutorUserId: undefined,
        actualExecutorUserName: undefined,
        finishTime: undefined,
        lastMaintenanceTime: undefined,
      },
      // 表单校验
      formRules: {
        faultContent: [{required: true, message: '故障内容不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态1-已完成0-未完成不能为空', trigger: 'blur'}],
        executeStatus: [{required: true, message: '执行状态0-未执行1-已开始2-暂停3-已结束不能为空', trigger: 'blur'}],
        actualExecutorUserId: [{required: true, message: '实际执行人id不能为空', trigger: 'blur'}],
        faultTypeId: [{required: true, message: '故障类型不能为空', trigger: 'change'}],
      },
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await MaintenanceRecordsApi.getMaintenanceRecords(id);
          this.formData = res.data;
          this.dialogTitle = "编辑设备维修记录";
          // 如果有实际执行人ID，需要显示对应的用户名
          if (this.formData.actualExecutorUserId) {
            await this.actualRemoteMethod(this.formData.actualExecutorUserName || '');
          }
          // 如果有设备ID，需要显示对应的设备名称
          if (this.formData.deviceId) {
            await this.deviceRemoteMethod(this.formData.deviceName || '');
          }
          // 设置故障类型路径
          if (this.formData.faultTypeId) {
            // 如果有故障类型ID，需要构建路径
            // 这里简化处理，实际可能需要递归获取完整路径
            this.faultTypePath = [this.formData.faultTypeId];
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        await this.deviceRemoteMethod('')
        await this.actualRemoteMethod('')
        this.dialogTitle = "新增设备维修记录";
      }
    },

    /** 动态加载故障类型子级数据 */
    async lazyLoadFaultType(node, resolve) {
      const { level, value } = node;
      const parentId = value || 0; // 如果是根节点，parentId为0

      try {
        const res = await FaultTypeApi.getFaultTypePage({
          pageSize: 100,
          parentId: parentId
        });

        // 处理返回的数据，转换为级联组件需要的格式
        // 对于fault-type页面，我们需要根据API返回的数据判断是否有子节点
        // 默认情况下，我们先假设所有节点可能有子节点，但在加载后会根据实际数据调整
        const nodes = res.data.list.map(item => ({
          value: item.id,
          label: item.faultTypeName,
          // 默认不设置leaf，让组件根据是否有children来判断
          // 存储额外信息
          faultTypeCode: item.faultTypeCode,
          faultTypeName: item.faultTypeName
        }));
        
        // 为每个节点预加载子节点，以确定是否是叶子节点
        // 对于每个节点，我们先检查是否有子节点
        for (let i = 0; i < nodes.length; i++) {
          try {
            // 提前查询该节点是否有子节点
            const childRes = await FaultTypeApi.getFaultTypePage({
              pageSize: 1,
              parentId: nodes[i].value
            });
            // 如果没有子节点，则设置为叶子节点
            if (!childRes.data.list || childRes.data.list.length === 0) {
              nodes[i].leaf = true;
            }
          } catch (error) {
            console.error('检查子节点失败', error);
            // 出错时默认设为叶子节点，避免不必要的展开
            nodes[i].leaf = true;
          }
        }

        // 通过调用resolve将子节点数据返回，通知组件数据加载完成
        resolve(nodes);
      } catch (error) {
        console.error('加载故障类型子级数据失败', error);
        resolve([]);
      }
    },

    /** 处理故障类型选择变化 */
    handleFaultTypeChange(value) {
      if (value && value.length > 0) {
        const selectedId = value[value.length - 1]; // 取最后一个选中的ID
        // 在选项树中查找选中的节点
        const selectedNode = this.findNodeInTree(this.faultTypeOptions, selectedId);
        if (selectedNode) {
          this.formData.faultTypeId = selectedNode.value;
          this.formData.faultTypeCode = selectedNode.faultTypeCode;
          this.formData.faultTypeName = selectedNode.faultTypeName;
          // 手动触发表单验证更新，解决第一次选择时仍提示的问题
          this.$nextTick(() => {
            if (this.$refs.formRef) {
              this.$refs.formRef.validateField('faultTypeId');
            }
          });
        } else {
          // 如果在已加载的树中找不到，通过API获取
          this.getFaultTypeById(selectedId).then(() => {
            // API获取成功后也触发表单验证更新
            this.$nextTick(() => {
              if (this.$refs.formRef) {
                this.$refs.formRef.validateField('faultTypeId');
              }
            });
          });
        }
      } else {
        // 清空选择
        this.formData.faultTypeId = undefined;
        this.formData.faultTypeCode = undefined;
        this.formData.faultTypeName = undefined;
        // 清空选择时也触发表单验证
        if (this.$refs.formRef) {
          this.$refs.formRef.validateField('faultTypeId');
        }
      }
    },

    /** 在树中查找节点 */
    findNodeInTree(tree, value) {
      for (const node of tree) {
        if (node.value === value) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeInTree(node.children, value);
          if (found) {
            return found;
          }
        }
      }
      return null;
    },

    /** 通过ID获取故障类型详情 */
    async getFaultTypeById(id) {
      try {
        const res = await FaultTypeApi.getFaultType(id);
        const faultType = res.data;
        this.formData.faultTypeId = faultType.id;
        this.formData.faultTypeCode = faultType.faultTypeCode;
        this.formData.faultTypeName = faultType.faultTypeName;
        return Promise.resolve(faultType);
      } catch (error) {
        console.error('获取故障类型详情失败', error);
        return Promise.reject(error);
      }
    },

    /** 实际执行人远程搜索方法 */
    async actualRemoteMethod(query) {
      this.actualUserLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          nickname: query // 根据用户名搜索
        };
        const response = await UserApi.listUser(params);
        this.actualUserList = response.data.list;
      } catch (error) {
        console.error('搜索实际执行人失败', error);
        this.actualUserList = [];
      } finally {
        this.actualUserLoading = false;
      }
    },

    /** 处理实际执行人选择 */
    handleActualExecutorChange(userId) {
      const selectedUser = this.actualUserList.find(user => user.id === userId);
      if (selectedUser) {
        this.formData.actualExecutorUserName = selectedUser.nickname;
      } else {
        this.formData.actualExecutorUserName = undefined;
      }
    },

    /** 设备远程搜索方法 */
    async deviceRemoteMethod(query) {
      this.deviceLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          deviceName: query,
        };
        const response = await DeviceApi.getDevicePage(params);
        this.deviceList = response.data.list;
      } catch (error) {
        console.error('搜索设备失败', error);
        this.deviceList = [];
      } finally {
        this.deviceLoading = false;
      }
    },

    /** 处理设备选择 */
    handleDeviceChange(deviceId) {
      const selectedDevice = this.deviceList.find(device => device.id === deviceId);
      if (selectedDevice) {
        this.formData.deviceName = selectedDevice.deviceName;
        this.formData.deviceCode = selectedDevice.deviceCode;
      } else {
        this.formData.deviceName = undefined;
        this.formData.deviceCode = undefined;
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await MaintenanceRecordsApi.updateMaintenanceRecords(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await MaintenanceRecordsApi.createMaintenanceRecords(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        deviceId: undefined,
        deviceCode: undefined,
        deviceName: undefined,
        faultTypeId: undefined,
        faultTypeCode: undefined,
        faultTypeName: undefined,
        faultContent: undefined,
        status: 0, // 新建时默认状态为0
        executeStatus: 0, // 新建时默认执行状态为0
        actualExecutorUserId: undefined,
        actualExecutorUserName: undefined,
        finishTime: undefined,
        lastMaintenanceTime: undefined,
      };
      this.faultTypePath = [];
      this.resetForm("formRef");
    }
  }
};
</script>
